<template>
  <div class="login-page">
    <m-form :rules="rules" class="form" :model="model" ref="formRef">
      <m-form-item prop="email" label="用户名" formText="账号规则">
        <m-input
          type="text"
          placeholder="请输入邮箱地址"
          v-model="model.email"
        />
      </m-form-item>
      <m-form-item prop="password" label="密码" formText="账号规则">
        <m-input
          type="password"
          placeholder="请输入密码"
          v-model="model.password"
        />
      </m-form-item>
      <m-form-item
        ><button
          @click.prevent="submitForm"
          class="btn btn-primary btn-block btn-large"
        >
          登录
        </button>
      </m-form-item>
    </m-form>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import MForm from '@/components/MForm';
import MFormItem from '@/components/MForm/MFormItem';
import MInput from '@/components/MForm/MInput';

export default {
  name: 'Login',
  components: {
    MForm,
    MFormItem,
    MInput,
  },
  setup() {
    const router = useRouter();
    const store = useStore();
    const rules = {
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
          type: 'email',
          message: '请输入正确的邮箱地址',
          trigger: ['blur', 'change'],
        },
      ],
      password: [{ required: true, message: '请输入与密码', trigger: 'blur' }],
    };
    const formRef = ref();
    const model = reactive({
      email: 'ceshi@qq.com',
      password: '12345678',
    });

    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          store
            .dispatch('login', model)
            .then(() => {
              router.push('/');
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    };

    return {
      rules,
      model,
      formRef,
      submitForm,
    };
  },
};
</script>

<style lang="scss">
.login-page {
  max-width: 330px;
  margin: 0 auto;
  .form {
    margin-top: 40px;
  }
}
</style>
